package com.rzjm.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.api.dao.*;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.ShopService;
import com.rzjm.api.service.SysUserService;
import com.rzjm.api.util.ElectricWeldingUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ShopServiceImpl extends BaseServiceImpl<ShopDao, Shop> implements ShopService {
    @Resource
    private ShopDao shopDao;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private DeviceDao deviceDao;
    @Resource
    private DeviceNodeDao deviceNodeDao;
    @Resource
    private PlatformDao platformDao;
    @Resource
    private TownsDao townsDao;
    @Resource
    private DeviceRangeDao deviceRangeDao;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private DeviceWeldingDao deviceWeldingDao;
    @Resource
    private ApplyShopDeviceRecordDao applyShopDeviceRecordDao;

    @Value("${web.imgprefix}")
    private String imgprefix;//图片地址

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址


    @Override
    public void uploadData(int platformId) {
        //企业信息上传
        Platform platform = platformDao.selectById(platformId);
        QueryWrapper<Shop> qw = new QueryWrapper<>();
//        qw.eq("platform_id", platformId);
        qw.isNotNull("social_code");
        qw.eq("is_upload", 2);
//        qw.gt("id", 1);
        List<Shop> list = shopDao.selectList(qw);
        if(CollUtil.isNotEmpty(list)){
            for (Shop shop : list) {
                Towns towns = townsDao.selectById(shop.getTownId());
                if (towns != null) {
                    if (StrUtil.isEmpty(towns.getAreaCode())) {
                        if (platformId == 1) {
                            shop.setAreaCode("370782001");
                        } else if (platformId == 2)  {
                            shop.setAreaCode("370781101");
                        } else if (platformId == 3) {
                            shop.setAreaCode("370783001");
                        } else if(platformId == 5){
                            shop.setAreaCode("370725001");
                        }else if(platformId == 7){
                            shop.setAreaCode("371482001");
                        }else if(platformId == 8){
                            shop.setAreaCode("3707DN401");
                        }else if(platformId == 9){
                            shop.setAreaCode("371482001");
                        }
                    } else {
                        shop.setAreaCode(towns.getAreaCode());
                    }
                }
//                shop.setIsUpload(1);
                shopDao.updateById(shop);
            }
            ElectricWeldingUtil.uploadCompany(list, platform,"U");
            for (Shop company : list){
                QueryWrapper<DeviceWelding> qwDevice = new QueryWrapper<>();
//                qwDevice.eq("platform_id", platformId);
                qwDevice.eq("shop_id", company.getId());
//                qwDevice.eq("is_has_breaker", 1);
//                qwDevice.isNotNull("fsr_breaker_id");
                List<DeviceWelding> deviceList = deviceWeldingDao.selectList(qwDevice);
                if(CollUtil.isNotEmpty(deviceList)){
                    for (DeviceWelding device : deviceList){
                        if(platformId == 2){
                            device.setProvNo("CYQZ0120240401" + device.getDeviceNo());
                        }else if(platformId == 1){
                            device.setProvNo("SDZC0120240401" + device.getDeviceNo());
                        }else if(platformId == 3){
                            device.setProvNo("SDQZ0120240401" + device.getDeviceNo());
                        }else if(platformId == 5){
                            device.setProvNo("SDCL0120240401" + device.getDeviceNo());
                        }else if(platformId == 6){
                            device.setProvNo("SDYN0120240401" + device.getDeviceNo());
                        }else if(platformId == 7){
                            device.setProvNo("SDFZ0120240401" + device.getDeviceNo());
                        }else if(platformId == 8){
                            device.setProvNo("SDXS0120240401" + device.getDeviceNo());
                        }else if(platformId == 9){
                            device.setProvNo("SDDZ0120240401" + device.getDeviceNo());
                        }
                        if(StrUtil.isEmpty(device.getDateOfManufacture())){
                            device.setDateOfManufacture("2023-10-20 00:00:00");
                        }

                        deviceWeldingDao.updateById(device);
                    }
                    //焊机设备
                    ElectricWeldingUtil.uploadDevice(company, deviceList, platform);
                    //智能终端设备信息上传
                    ElectricWeldingUtil.uploadDeviceIot(company,deviceList, platform);
                }

                //焊工信息上报
                QueryWrapper<SysUser> qwUser = new QueryWrapper<>();
                qwUser.eq("shop_id", company.getId());
                qwUser.ne("certificate_num", "");
//                qwUser.ne("certificate_img", "");
                qwUser.isNotNull("sign_organ");
                qwUser.isNotNull("sign_organ_type");
                qwUser.isNotNull("certificate_num");
//                qwUser.isNotNull("certificate_img");
                List<SysUser> sysUserList = sysUserDao.selectList(qwUser);
                if(CollUtil.isNotEmpty(sysUserList)){
                    // 焊工上传
                    ElectricWeldingUtil.uploadOperationInfo(company, sysUserList, platform);
                    // 焊工证上传
                    ElectricWeldingUtil.uploadCertificateInfo(company, sysUserList, platform, uploadPath);
                }
            }
        }
    }

    @Override
    public Shop selectByUserId(Integer user_id) {
        Shop shop = shopDao.selectOneByColumn("user_id",user_id);
        if(shop != null){
            if(shop.getShopLogo() != null && !shop.getShopLogo().equals("")){
                shop.setShopLogo(imgprefix + shop.getShopLogo());
            }
        }
        return shop;
    }

    @Override
    public Shop selectById(Integer id) {
        Shop shop = shopDao.selectById(id);
        return getShop(shop,0);
    }

    @Override
    public Shop selectById(Integer id, Integer bx_shop_id) {
        Shop shop = shopDao.selectById(id);
        shop = getShop(shop,bx_shop_id);
        return shop;
    }

    @Override
    public List<Shop> selectMyList(User user, Integer state, String keyword, Integer shop_type, Integer device_type, Integer position, Integer pageIndex, Integer pageSize) {
        List<Shop> shops = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if(user.getIsTest() == 1){
            if(shop_type > 0){
                map.put("shop_type",shop_type);
            }
            int offset = (pageIndex - 1) * pageSize;
            if(StrUtil.isNotEmpty(keyword)){
                map.put("shop_name", keyword);
            }
            shops = shopDao.getListByAdminUserId(map,offset,pageSize);
        }else{
            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser != null){
                if(sysUser.getUserType() >= 4){
                    map.put("id",sysUser.getShopId());
                    if(shop_type > 0){
                        map.put("shop_type",shop_type);
                    }
                    Shop shop = shopDao.selectById(sysUser.getShopId());
                    if(shop!= null){
                        shops.add(shop);
                    }
                } else if(sysUser.getUserType() == 0 || sysUser.getUserType() == 1){//系统管理员   平台管理员
                    if(shop_type > 0){
                        map.put("shop_type",shop_type);
                    }
                    if(StrUtil.isNotEmpty(keyword)){
                        map.put("shop_name", keyword);
                    }

                    int offset = (pageIndex - 1) * pageSize;
                    shops = shopDao.getListByAdminUserId(map,offset,pageSize);
                } else if(sysUser.getUserType() == 2){//集团管理员
                    if(shop_type > 0){
                        map.put("shop_type",shop_type);
                    }
                    if(StrUtil.isNotEmpty(keyword)){
                        map.put("shop_name", keyword);
                    }
                    map.put("group_id",sysUser.getGroupId());
                    int offset = (pageIndex - 1) * pageSize;
                    shops = shopDao.getListByAdminUserId(map,offset,pageSize);
                } else if(sysUser.getUserType() == 3){//片区管理员
                    if(shop_type > 0){
                        map.put("shop_type",shop_type);
                    }
                    if(StrUtil.isNotEmpty(keyword)){
                        map.put("shop_name", keyword);
                    }
                    map.put("pianqu_id",sysUser.getPianquId());
                    int offset = (pageIndex - 1) * pageSize;
                    shops = shopDao.getListByAdminUserId(map,offset,pageSize);
                }
                else {
                    map.put("sys_user_id",sysUser.getUserId());
                    if(shop_type > 0){
                        map.put("shop_type",shop_type);
                    }

                    if(StrUtil.isNotEmpty(keyword)){
                        map.put("shop_name", keyword);
                    }

                    int offset = (pageIndex - 1) * pageSize;
                    shops = shopDao.getListByUserId(map,offset,pageSize);
                }

            }
        }
        if(CollUtil.isNotEmpty(shops)){
            for (Shop shop : shops){
                if(shop_type == 5){
                    QueryWrapper<DeviceRange> qwDevice = new QueryWrapper<>();
                    qwDevice.eq("shop_id",shop.getId());
                    qwDevice.eq("device_type",device_type);
                    long deviceCount = deviceRangeDao.selectCount(qwDevice);
                    shop.setDeviceCount(deviceCount);
                }else {
                    if(shop.getDeviceShowType() == 0){
                        QueryWrapper<Device> qwDevice = new QueryWrapper<>();
                        qwDevice.eq("shop_id",shop.getId());
//                        if(device_type == 2){
                            qwDevice.eq("position_type", position);
//                        }
                        long deviceCount = deviceDao.selectCount(qwDevice);
                        shop.setDeviceCount(deviceCount);
                    }else{
                        QueryWrapper<DeviceNode> qwDevice = new QueryWrapper<>();
                        qwDevice.eq("shop_id",shop.getId());
//                        if(device_type == 2){
                            qwDevice.eq("position_type", position);
//                        }
                        long deviceCount = deviceNodeDao.selectCount(qwDevice);
                        shop.setDeviceCount(deviceCount);
                    }
                }
            }
        }
        return shops;
    }

    public List<Shop> selectApplyMyList(User user, Integer state, String keyword, Integer shop_type, Integer device_type, Integer position, Integer pageIndex, Integer pageSize) {
        List<Shop> shops = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();

        Date date = new Date();
        QueryWrapper<ApplyShopDeviceRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.eq("req_user_id", user.getId());
        recordQueryWrapper.eq("req_user_id", user.getId());
        recordQueryWrapper.eq("examine_state", 1);
        recordQueryWrapper.isNotNull("effect_time");
        recordQueryWrapper.gt("effect_time", date);
        if (position == 1){
            recordQueryWrapper.like("apply_device_type", "1");
        }else if (position == 2){
            recordQueryWrapper.like("apply_device_type", "2");
        }else{
            return shops;
        }
        List<ApplyShopDeviceRecord> recordList = applyShopDeviceRecordDao.selectList(recordQueryWrapper);
        if (recordList == null || recordList.size() == 0){
            return shops;
        }
        List<Integer> shopIds = recordList.stream().map(r -> r.getApplyShopId()).collect(Collectors.toList());

        Page<Shop> page = new Page<>(pageIndex,pageSize);
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", shopIds);
        if(StrUtil.isNotEmpty(keyword)){
            queryWrapper.like("shop_name", keyword);
        }
        IPage<Shop> list = page(page,queryWrapper);
        shops = list.getRecords();

        if(CollUtil.isNotEmpty(shops)){
            for (Shop shop : shops){
                if(shop_type == 5){
                    QueryWrapper<DeviceRange> qwDevice = new QueryWrapper<>();
                    qwDevice.eq("shop_id",shop.getId());
                    qwDevice.eq("device_type",device_type);
                    long deviceCount = deviceRangeDao.selectCount(qwDevice);
                    shop.setDeviceCount(deviceCount);
                }else {
                    if(shop.getDeviceShowType() == 0){
                        QueryWrapper<Device> qwDevice = new QueryWrapper<>();
                        qwDevice.eq("shop_id",shop.getId());
//                        if(device_type == 2){
                            qwDevice.eq("position_type", position);
//                        }
                        long deviceCount = deviceDao.selectCount(qwDevice);
                        shop.setDeviceCount(deviceCount);
                    }else{
                        QueryWrapper<DeviceNode> qwDevice = new QueryWrapper<>();
                        qwDevice.eq("shop_id",shop.getId());
//                        if(device_type == 2){
                            qwDevice.eq("position_type", position);
//                        }
                        long deviceCount = deviceNodeDao.selectCount(qwDevice);
                        shop.setDeviceCount(deviceCount);
                    }
                }
            }
        }
        return shops;
    }

    private Shop getShop(Shop shop,Integer bx_shop_id){
        if(shop != null){
            if(shop.getShopLogo() != null && !shop.getShopLogo().equals("")){
                shop.setShopLogo(imgprefix + shop.getShopLogo());
            }
//            QueryWrapper<Shop> qw = new QueryWrapper<>();
//            qw.eq("shop_id",shop.getId());
//            qw.eq("state",1);
//            if(bx_shop_id == 0){
//                qw.eq("is_exclusive",0);
//            }
        }
        return shop;
    }

    @Override
    public List<Shop> selectByState(Integer state, Integer shopType,Integer offset, Integer pageSize,double longitude,double latitude) {
        List<Shop> list = shopDao.selectByState(state,shopType,offset,pageSize,longitude,latitude);
        return list;
    }

    @Override
    public List<Shop> selectByStateAndServiceType(Integer service_type,Integer state, Integer offset, Integer pageSize, double longitude, double latitude) {
        List<Shop> list = shopDao.selectByStateAndServiceType(service_type,state,offset,pageSize,longitude,latitude);
        return list;
    }

    @Override
    public List<Shop> selectBySearch(String shop_name,Integer shop_type, Integer state, Integer offset, Integer pageSize,double longitude,double latitude) {
        List<Shop> list = shopDao.selectBySearch(shop_name,shop_type, state,offset,pageSize,longitude,latitude);
        return list;
    }

    @Override
    public List<Shop> getListByAdminUserId(Map<String, Object> map) {
        return shopDao.getListByAdminUserId(map,null,null);
    }
}
